package com.cxs.config;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Project: wechat-push
 * @Author: cxs2014501@163.com
 * @Create: 2023/9/7 11:40
 * @Description:
 * 解决：RestTemplate自带的HttpMessageConverters中没用能处理
 * content-type=application/javascript的response的HttpMessageConverter
 **/
public class MyApplicationJavascriptHttpMessageConverter extends AbstractHttpMessageConverter {
    /**
     * restTemplate获得的响应的content-type满足下面的条件
     * 才会被该HttpMessageConverter处理
     */
    public MyApplicationJavascriptHttpMessageConverter() {
        // application/javascript
        super(new MediaType("application", "javascript", Charset.forName("UTF-8")));
    }

    /**
     * 检查传入的字节码是否符合要求
     *
     * @param clazz
     * @return 返回true才会执行readInternal()
     */
    @Override
    protected boolean supports(Class clazz) {
        return true;
    }

    /**
     * 将restTemplate获得的响应转化成clazz对应的类型
     *
     * @param clazz
     * @param inputMessage restTemplate获得的响应
     * @return
     */
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        //restTemplate发送请求后获得的响应
        InputStream body = inputMessage.getBody();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = body.read(buffer))) {
            output.write(buffer, 0, n);
        }
        //将响应转成对应类型
        return JSON.parseObject(new String(output.toByteArray()), clazz);
    }

    /**
     * 还不知道该方法的功能
     * 该方法也不会被执行到
     *
     * @param o
     * @param outputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //do nothing
        System.out.println("do nothing");
    }
}
